package com.gin.ehdownloader.config;

import com.gin.api.EhApi;
import com.gin.api.EhClient;
import com.gin.aria2.main.Aria2Api;
import com.gin.aria2.main.Aria2Client;
import com.gin.ehdownloader.interceptor.LoggingInterceptor;
import com.gin.ehdownloader.props.Aria2Properties;
import com.gin.ehdownloader.utils.FileIoUtils;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 配置
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/3/14 11:21
 */
@Configuration
public class ApiConfig {
    @Bean
    public Aria2Api aria2Api(Aria2Client aria2Client) throws IOException {
        // 开启参数打印
//        aria2Client.setPrintParam(true);
        return new Aria2Api(aria2Client);
    }

    @Bean
    public Aria2Client aria2Client() throws IOException {
        File file = new File("./aria2.json");
        final Aria2Properties props = file.exists() ? FileIoUtils.readObj(file, Aria2Properties.class) : new Aria2Properties();
        return new Aria2Client(null, props.getHost(), props.getToken());
    }

    @Bean
    public EhApi ehApi(EhClient ehClient) throws FileNotFoundException {
        return new EhApi(ehClient);
    }

    @Bean
    public EhClient ehClient() throws FileNotFoundException {
        final OkHttpClient client = EhClient.defaultClient().newBuilder().addInterceptor(new LoggingInterceptor()).build();
        final String cookie = FileIoUtils.readStr(new File("./cookie.txt"));
        return new EhClient(client, cookie, EhClient.defaultProxy());
    }
}   
